<%@ page language="java" import="java.util.*" contentType="text/html" pageEncoding="UTF-8"%>
<jsp:useBean id="cp" class="bcnet.service.StockManager"/>
<%@ page import="com.google.appengine.api.users.User" %>
<%@ page import="com.google.appengine.api.users.UserService" %>
<%@ page import="com.google.appengine.api.users.UserServiceFactory" %>
<% request.setCharacterEncoding("UTF-8"); 
	UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();
    String userCode[] = new String[2];
    userCode = cp.getCode(user);
    String code = userCode[0];
    String refreshRate = userCode[1];
%>

<html>
<head>
<title>Bunchannet</title> 
<link type="text/css" rel="stylesheet" href="/stylesheets/main.css" />
<script type="text/javascript"> 


function onlyNumbersAndComma(evt){
	var e = event || evt; // for trans-browser compatibility
	var charCode = e.which || e.keyCode;
	if ((charCode >= 48 && charCode <= 57) || charCode == 44 || charCode == 72 || charCode == 104 || charCode == 66 || charCode == 98 || charCode == 83 || charCode == 115){
		return true;
	}
	else if (charCode == 13){
		//addNewCode(document.getElemetById('addCode').value);
		addNewCode(document.getElementById("addCode").value);
		//ajaxFunction(0);initRefreshIntervalId();
	}
	return false;
}

function onlyNumbers(evt){
	var e = event || evt; // for trans-browser compatibility
	var charCode = e.which || e.keyCode;
	if ((charCode >= 48 && charCode <= 57) || charCode == 72 || charCode == 104 || charCode == 66 || charCode == 98){
		return true;
	}
	else if (charCode == 13){
		addNewCode(document.getElementById('addCode').value);
	}
	return false;
}

function toggle_visibility(id1, id2) {
	var e = document.getElementById(id1);
	var f = document.getElementById(id2);
	$(document).ready(function(){
		if(e.style.display == 'block' || e.style.display == 'inline-block' || e.style.display == ''){
			$(e).slideToggle("normal");
          	f.innerHTML = '▼';
		}
		else{
			$(e).slideToggle("normal");
			e.style.display = 'inline-block';
			f.innerHTML = '▲';
		}
	});
}

function addNewCode(addCode) {
	
	if(addCode.length>0){
		var addCodeArray = addCode.split(",");
		for(i=0; i<addCodeArray.length; i++){
			if($("#poolresult"+addCodeArray[i]).length==0){ // not duplicate in current list
			
				var existingCode = document.getElementById("code").value;
				var newCode = existingCode + ","+addCodeArray[i]
	
				newCode = newCode.replace(",,",",");
				newCode = (newCode[0] == ',') ? newCode.substr(1) : newCode;
				newCode = (newCode[newCode.length-1] == ',') ? newCode.substr(0,newCode.length-1) : newCode;
			
				document.getElementById("code").value = newCode;
			
				$("#poolresult0").append('<div id="poolresult'+addCodeArray[i]+'" name="poolresult'+addCodeArray[i]+'"></div>');
				$("#poolresult"+addCodeArray[i]).append('<div class="code"><span id="loading'+addCodeArray[i]+'"></span><span id="animating'+addCodeArray[i]+'"></span></div>');
				$("#poolresult0").append('<hr id="hr'+addCodeArray[i]+'">');
				ajaxFunction(addCodeArray[i]);
			}
		}
	}
	document.getElementById("addCode").value = "";	
}

function togglePriceChart(code,np) {
	if ($("#priceChart"+code).is(':empty')){
		$("#priceChart"+code).html("<iframe seamless style=\"width: 100%; height:220px; border: none; background-color: transparent;\" src=\"/priceChart.jsp?code="+code+"&np="+np+"&chartHeight=200\"></iframe><br>");
	}
	else{
		$("#priceChart"+code).html("");		
	}
}

function deleteCode(inputCode) {
	var existingCode = document.getElementById("code").value;
	//console.log("before delete "+existingCode);
	var newCode = existingCode.replace(inputCode,"");

	newCode = newCode.replace(",,",",");
	newCode = (newCode[0] == ',') ? newCode.substr(1) : newCode;
	newCode = (newCode[newCode.length-1] == ',') ? newCode.substr(0,newCode.length-1) : newCode;

	document.getElementById("code").value = newCode;
	$("#poolresult"+inputCode).remove();
	$("#hr"+inputCode).remove();
	//console.log("after delete "+newCode);
	//if(newCode.length>0){
	//	ajaxFunction(0);initRefreshIntervalId();
	//}
	
}

document.onkeypress = onlyNumbersAndComma;
//document.onkeypress = onlyNumbers;

</script>

<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="pragma" content="no-cache">
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no" >
<meta name="HandheldFriendly" content="True">
<META HTTP-EQUIV="Expires" CONTENT="-1">

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-20092428-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

</head>

<% //if (user != null){ %>
	<body onload="ajaxFunction(0);initRefreshIntervalId();">
<% //} else { %>
<!-- <body> -->
<% //} %>
	

<script type="text/javascript">

var refreshIntervalId = new Array();

function initRefreshIntervalId() {
	var code = document.myForm.code.value;
	var codeArr = code.split(",");
	
	// clear all refresh everytime mass refresh
	for (var j = 0; j < refreshIntervalId.length; j++){
		if( typeof(refreshIntervalId[j]) == 'undefined' || refreshIntervalId[j] == null) {
			//do nth
		}
		else {
			clearInterval(refreshIntervalId[j]);
		}
	}
	// init the refresh size again
	refreshIntervalId = new Array(codeArr.length);
	
	var refreshString = getRefreshValue(code);
	var refreshArr = refreshString.split(",");
	for(var i = 0; i < codeArr.length; i++) {
		if(refreshArr[i] == "stop"){
			// do nth
		}
		else {
			refreshIntervalId[i] = setInterval("ajaxFunction('"+codeArr[i]+"')",document.getElementById("refreshRate"+codeArr[i]).value);
		}
	}
}

function getVisibilityValue(codeInput) {
	//var code = document.myForm.code.value;
	var code = codeInput;
	var codeArr = code.split(",");
	var e;
	var result = "";
	for(var i = 0; i < codeArr.length; i++) {
		//alert(codeArr[i]);
		e = document.getElementById('detail'+codeArr[i]);
		if( typeof(e) == 'undefined' || e == null) {
			result += "0,";
		}
		else {
			if(e.style.display == 'none' || e.style.display == '') {
				result += "0,";
			}
			else { 
				result += "1,";
			}
		}
	}
	return result.substring(0,result.length-1);
}


function getRefreshValue(codeInput) {
	var code = codeInput;
	var codeArr = code.split(",");
	var e;
	var result = "";
	for(var i = 0; i < codeArr.length; i++) {
		//alert(codeArr[i]);
		e = document.getElementById('refreshRate'+codeArr[i]);
		if( typeof(e) == 'undefined' || e == null) {
			result += "stop,";
		}
		else {
			result += e.value+",";
		}
	}
	//alert(result)
	return result.substring(0,result.length-1);
}

function stopRefresh(codeInput) {
	//alert(refreshIntervalId);
	var code = document.myForm.code.value;
	var codeArr = code.split(",");
	for(var i = 0; i < codeArr.length; i++) {
		if(codeInput == codeArr[i]) {
			//alert("codeInput="+codeInput);
			//alert("codeArr="+codeArr[i]);
			//alert("i="+i);
			clearInterval(refreshIntervalId[i]);
			if(isNaN(document.getElementById("refreshRate"+codeInput).value)){
				//alert(refreshIntervalId.length);
				//do nth
			}
			else{
				//alert(refreshIntervalId.length);
				refreshIntervalId[i] = setInterval("ajaxFunction('"+codeInput+"')",document.getElementById("refreshRate"+codeInput).value);
			}
		}
	}
}

function ajaxFunction(input){
	//console.log("clicked");
var xmlhttp;
var code;
if(input == 0){
	code = document.myForm.code.value;
}
else {
	code = input;
}	

if (window.XMLHttpRequest)
  {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else if (window.ActiveXObject)
  {
  // code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
else
  {
  alert("Your browser does not support XMLHTTP!");
  }
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==0 || xmlhttp.readyState==1 || xmlhttp.readyState==2 || xmlhttp.readyState==3 )
  {
  //document.getElementById("loading"+input).innerHTML='<img width="16" height="16" src="images/ajax-loader.gif">';
	document.getElementById("loading"+input).style.display='none';
	document.getElementById("animating"+input).style.display='inline-block';
  }
if(xmlhttp.readyState==4)
  {
  if(input == 0){
	  document.getElementById("loading"+input).style.display='inline-block';
	  document.getElementById("animating"+input).style.display='none';
	  
  	//document.getElementById("loading"+input).innerHTML='<img width="16" height="16" src="images/ajax-loader-static.gif" onclick="ajaxFunction('+input+');initRefreshIntervalId();"/>';
  }
  else {
	  document.getElementById("loading"+input).style.display='inline-block';
	  document.getElementById("animating"+input).style.display='none';
  	//document.getElementById("loading"+input).innerHTML='<img width="16" height="16" src="images/ajax-loader-static.gif" onclick="ajaxFunction('+input+');"/>';
  }
  document.getElementById("poolresult"+input).innerHTML=xmlhttp.responseText;
  }
}
xmlhttp.open("GET","stockQuote.jsp?code="+code+"&detail="+getVisibilityValue(code)+"&refresh="+getRefreshValue(code)+"&input="+input+"&dummy="+new Date().getTime(),true);
xmlhttp.send(null);
}

function ajaxFunction2(){
var xmlhttp;
if (window.XMLHttpRequest)
  {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else if (window.ActiveXObject)
  {
  // code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
else
  {
  alert("Your browser does not support XMLHTTP!");
  }
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==0 || xmlhttp.readyState==1 || xmlhttp.readyState==2 || xmlhttp.readyState==3 )
  {
  document.getElementById('message').innerHTML='Saving...';
  }
if(xmlhttp.readyState==4)
  {
  document.getElementById('message').innerHTML=xmlhttp.responseText;
  setTimeout("document.getElementById('message').innerHTML='&nbsp;'",3000);
  }
}
//xmlhttp.open("GET","saveCode.jsp?code="+document.myForm.code.value+"&refresh="+document.getElementById('refreshRate').options[document.getElementById('refreshRate').selectedIndex].value+"&dummy="+new Date().getTime(),true);
xmlhttp.open("GET","saveCode.jsp?code="+document.myForm.code.value+"&dummy="+new Date().getTime(),true);
xmlhttp.send(null);
}


<%// if (!refreshRate.equals("stop")){ %>
// refreshIntervalId = setInterval("ajaxFunction()",<%=refreshRate%>);
<%// } %>

</script>


<form name="myForm" action="">
<% //if (user != null) { %>
<div class="message" id="message">&nbsp;</div>
<div>
<input id="code" type="hidden" name="code" value="<%=code%>" />
<input id="addCode" type="text" name="addCode" placeholder="Code" />
<button type="button" onClick="addNewCode(document.getElementById('addCode').value);">+</button>
<span id="loading0" name="loading0" style="display: inline-block;"><img src="images/ajax-loader-static.gif" onclick="ajaxFunction(0);initRefreshIntervalId();"/></span>
<span id="animating0" name="animating0" style="display: none;"><img src="images/ajax-loader.gif" /></span>
</div>
<HR/>
<div id="poolresult0" name="poolresult0" >
</div>

<%
	//}
%>
<BR/>
<%
	out.println(cp.genLoginLogoutUrl(request.getRequestURI()));
%>
</form>
<div class="tips">
<!--  <a target="_blank" href="https://docs.google.com/spreadsheets/d/1lMaRMF7WIHXt9ZfGnooJ3m8GySHCFKwzZEMDhRz-2nI/edit?usp=sharing">Tips</a><br/> -->
<a target="_blank" href="/cron/addTask.jsp">Refresh Buy Sell List</a><br/>
<a target="_blank" href="/cron/clearCache.jsp">Clear Cache</a><br/>
<a target="_blank" href="/cron/refreshFullCodeList.jsp">Refresh Full Code List</a><br/>
<a target="_blank" href="/addBoughtCode.jsp">Add Bought Code</a><br/>

</div>
<br/>
<div class="copyright">&copy;2015 Bunchannet</div>

</body>
</html>
 